package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.domian.Category;
import com.itheima.domian.Dish;
import com.itheima.domian.DishFlavor;
import com.itheima.dto.DishDto;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    DishService dishService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    DishFlavorService dishFlavorService;
    @Autowired
    RedisTemplate redisTemplate;

    //新增方法
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {

        //自己创建方法 将两张表的数据传递进去
        dishService.saveWithFlavor(dishDto);
        String rediskey = dishDto.getCategoryId() + "Dishlist";
        redisTemplate.delete(rediskey);
        return R.success("菜品添加成功");
    }

    //分页查询
    @GetMapping("page")
    public R<Page<DishDto>> page(Integer page, Integer pageSize, String name) {
        Page<Dish> dishPage = new Page<>(page, pageSize);
        dishService.page(dishPage, Wrappers.<Dish>lambdaQuery().like(StringUtils.isNotBlank(name), Dish::getName, name).orderByDesc(Dish::getUpdateTime));

        //创建第二个分页查询
        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");

        List<DishDto> collect = dishPage.getRecords().stream().map(dish -> {
            DishDto dishDto = new DishDto();
            //将数据拷贝到这个类
            BeanUtils.copyProperties(dish, dishDto);
            //根据分类菜单 的菜品id查询出对应的数据
            Category category = categoryService.getById(dishDto.getCategoryId());
            dishDto.setCategoryName(category.getName());
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(collect);
        return R.success(dishDtoPage);
    }

    //修改数据回显
    @GetMapping("{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    //修改数据
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        String rediskey = dishDto.getCategoryId() + "Dishlist";
        redisTemplate.delete(rediskey);
        return R.success("修改成功");
    }

    //批量启用
    @PostMapping("/status/1")
    public R<String> status(Long[] ids) {
        LambdaQueryWrapper<Dish> queryWrapper = Wrappers.<Dish>lambdaQuery().in(Dish::getId, Arrays.asList(ids));
        Dish dish = new Dish();
        dish.setStatus(1);
        dishService.update(dish, queryWrapper);
        for (Long id : ids) {
            Dish dish1 = dishService.getById(id);
            System.out.println(dish1);
            String rediskey = dish1.getCategoryId() + "Dishlist";
            redisTemplate.delete(rediskey);
        }
        return R.success("批量启用成功");
    }

    //批量禁用
    @PostMapping("/status/0")
    public R<String> status1(Long[] ids) {
        LambdaQueryWrapper<Dish> queryWrapper = Wrappers.<Dish>lambdaQuery().in(Dish::getId, ids);
        Dish dish = new Dish();
        dish.setStatus(0);
        dishService.update(dish, queryWrapper);
        for (Long id : ids) {
            Dish dish1 = dishService.getById(id);
            System.out.println(dish1);
            String rediskey = dish1.getCategoryId() + "Dishlist";
            redisTemplate.delete(rediskey);
        }
        return R.success("批量禁用成功");
    }

    //批量删除
    @DeleteMapping
    public R<String> delete(Long[] ids) {
        dishService.delete(ids);
        return R.success("删除成功");
    }

    //根据id查询菜品
    @GetMapping("list")
    public R<List<DishDto>> list(Dish dish) {
        //判断用户是否第一次 查询菜品 如果是 就去数据库查询  如果不是 就将数据从Redis中获取
        String rediskey = dish.getCategoryId() + "Dishlist";
        List<DishDto> dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(rediskey);
        if (dishDtos != null) {
            return R.success(dishDtos);
        }
        //查询出对应的菜品  还有口味
        LambdaQueryWrapper<Dish> queryWrapper = Wrappers.<Dish>lambdaQuery().eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId()).eq(Dish::getStatus, 1);
        //查询口味
        List<Dish> list = dishService.list(queryWrapper);
        List<DishDto> dtoList = new ArrayList<>();

        for (Dish dish1 : list) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish1, dishDto);
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = Wrappers.lambdaQuery(DishFlavor.class).eq(dish1.getId() != null, DishFlavor::getDishId, dish1.getId());
            List<DishFlavor> list1 = dishFlavorService.list(queryWrapper1);
            dishDto.setFlavors(list1);
            dtoList.add(dishDto);
        }
        // 第一次 将菜品存入Redis数据库
        redisTemplate.opsForValue().set(rediskey, dtoList, 60, TimeUnit.MINUTES);
        return R.success(dtoList);
    }


}
